package com.zxw.websocket.server;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @projectName: erp-cloud
 * @package: com.zxw.websocket.server
 * @className: WsServerEndpoint
 * @author: zhangxuewei
 * @description: TODO
 * @date: 2023/10/30 11:29
 * @version: 1.0
 */

@ServerEndpoint(value = "/chat")
@Component
public class WsServerEndpoint {

    private static CopyOnWriteArrayList<WsServerEndpoint> webSocketSet = new CopyOnWriteArrayList<>();
    private Session session;

    @OnOpen
    public void onOpen(Session session) {
        System.out.println("WebSocket opened: " + session.getId());
        this.session = session;
        webSocketSet.add(this);
    }

    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        System.out.println("Received message: " + message);
        session.getBasicRemote().sendText(message);
//        for (WsServerEndpoint item : webSocketSet) {
//            item.sendMessage(session.getId() + ": " + message);
//        }
    }

    @OnClose
    public void onClose(Session session) {
        System.out.println("WebSocket closed: " + session.getId());
        webSocketSet.remove(this);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("WebSocket error: " + error.getMessage());
    }

    private void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }
}